#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>

#define BUF_SIZE 100

int main(int argc, const char * argv[]) {
    
    char filename[100] = {0};
    printf("input filename to save:");
    gets(filename);
    FILE* fp = fopen(filename, "wb");
    if (fp == nullptr) {
        printf("Cannot open file, press any key to exit!\n");
        exit(0);
    }
    
    int sock = socket(AF_INET, SOCK_STREAM, 0);
    
    struct sockaddr_in serv_addr;
    memset(&serv_addr, 0, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
    serv_addr.sin_port = htons(1234);
    connect(sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr));
    
    char buffer[BUF_SIZE] = {0};
    int nCount;
    while ((nCount = read(sock, buffer, BUF_SIZE)) > 0) {
        fwrite(buffer, nCount, 1, fp);
        printf("接受中。。。\n");
    }
    printf("File transfer success!\n");
    
    fclose(fp);
    close(sock);
    
    return 0;
}
